import { defineStore } from "pinia";
import { v4 as uuidv4 } from "uuid";

const useChatState = () => {
  const chatMap = useMyLocalStorage<ChatMap>(
    "chatMap",
    new Map([["0", { id: "0", name: "_blank", messages: {}, show: false }]])
  );
  const currentChat = useMyLocalStorage<string>("currentChat", "0");
  return {
    chatMap,
    currentChat,
  };
};
export const chatStore = defineStore("chatStore", () => {
  const chatState = useChatState();
  const { chatMap, currentChat } = chatState;
  const clearChatList = () => {
    chatMap.value.clear();
  };
  const getChat = (id: string | number) => {
    return chatMap.value.get(id);
  };
  const setChat = (id?: string, value?: Chat) => {
    const randomId = uuidv4();
    const chat = {
      id: randomId,
      name: "未命名",
      messages: {},
    };
    chatMap.value.set(id ? id : randomId, value ? value : chat);
    return value ? value : chat;
  };
  const addChatMessages = (chatId: string | number, message: Message) => {
    const messageId = uuidv4();
    chatMap.value.get(chatId)!.messages[messageId] = {
      ...message,
      id: messageId,
      createdAt: Date.now().toString(),
      updatedAt: Date.now().toString(),
    };

    return messageId;
  };
  const deleteChat = (id: string) => {
    chatMap.value.delete(id);
  };
  const setCurrentChat = (value: string) => {
    currentChat.value = value;
  };
  return {
    ...chatState,
    addChatMessages,
    getChat,
    setChat,
    clearChatList,
    deleteChat,
    setCurrentChat,
  };
});
